import Vue from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import VueCookie from 'vue-cookie';
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import NProgress from 'nprogress' // Progress 进度条
import Moment from 'moment';
import 'element-ui/lib/theme-chalk/index.css';
import 'font-awesome/css/font-awesome.css';
import 'nprogress/nprogress.css'// Progress 进度条样式
import '@/assets/css/main.css';
import '@/assets/css/reset.css';
import Func from '@/utils/function';


import VueLocalStorage from 'vue-localstorage';

Vue.use(VueLocalStorage);
Vue.use(VueCookie);
Vue.use(ElementUI);
Vue.use(Func);

// Vue.prototype.pageLayout = 'total, sizes, prev, pager, next, jumper'
Vue.prototype.pageLayout = 'prev, pager, next, jumper'
Vue.prototype.pagePageSizes = [10, 20, 30]
Vue.prototype.pagePageSize = 10

Vue.prototype.$store = store;
Vue.prototype.moment = Moment;
Vue.config.productionTip = false;

router.beforeEach((to, from, next) => {
    NProgress.start();//开启进度条
    if (to.meta.title){
        document.title = '医单云系统-' + to.meta.title;//动态化每个页面的标题
        store.dispatch('setMetaName', to.meta.title);
        store.dispatch('setActive', to.path);
    }
    const whiteList = ['Login'];
    const token = VueCookie.get('token');
    if (token) {
        //如果令牌存在，不能直接访问登录界面
        if (to.matched.some(m => m.meta.login)) {
            next({name: 'Main'});
        } else {
            //动态路由只挂载一次
            if (store.getters.routers.length) {
                next();
            } else {
                store.dispatch('generateRoutes').then(() => {
                    router.addRoutes(store.getters.routers); // 动态添加可访问路由表
                    next({...to});//hack方法 确保addRoutes已完成
                });
            }
        }
    } else {
        //登录白名单，在执行next({name:'Login'})的时候允许进入该页面
        if (whiteList.includes(to.name)) {
            next();
        } else {
            next({name: 'Login'});// token不存在的情况全部重定向到登录页
        }
    }
});

// NProgress.configure({ showSpinner: false });//取消右上角的进度环
router.afterEach((transition) => {
    NProgress.done();//关闭进度条
});

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')
